#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (c) 2011
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Author: Jesus Carrero <j.o.carrero@gmail.com>
# Mountain View, CA
#

""" convection diffusion reaction solver in 1D, finite element. """

from scipy import asarray, zeros
from scipy.sparse.construct import spdiags
from scipy.sparse.linalg import spsolve as spsolve

from utils.Grid import Grid1D
from utils.ProjOperators import oned_inner

from AssembleStiffnesMassMatrices import AssembleStiffnesMassMatrices


class SecondOrderStatic1D(object):

    """
    solve the boundary value problem:

    a*Uxx+b*Ux+cU = f
    U[xleft] = uxleft
    U[xright] = uxright

  """

    __slots__ = [
        'm_ass_stiff',
        'm_basis',
        'm_mesh',
        'm_left_bd',
        'm_load',
        'm_mass_diag',
        'm_quads',
        'm_right_bd',
        'm_stiff_diag',
        'm_ul',
        'm_ur',
        ]

    def __init__(self, nsegs, xleft, xright):
        """
      m_stiff_diag ~ stiffnes as sparse diag matrix
      m_basis ~ finite element space
      m_mesh ~ mesh structure
      m_left_bd ~ Boundary term left hand side
      m_load ~ force term f(x, t)
      m_mass_diag ~ mass as sparse diag matrix
      m_quads ~ quadrature formulas
      m_right_bd ~ Boundary term right hand side
      m_stiff_diag ~ stiff matrix in diagonal-vector format
      m_ul ~ left boundary condition (real number).
      m_ur ~ right boundary condition (real number).
    """

        (self.m_basis, self.m_quads) = (None, None)
        (self.m_left_bd, self.m_right_bd) = (None, None)
        (self.m_mass_diag, self.m_stiff_diag) = (None, None)
        (self.m_load, self.m_ul, self.m_ur) = (None, None, None)

        self.m_mesh = Grid1D(nsegs, xleft, xright)
        self.m_ass_stiff = AssembleStiffnesMassMatrices(self.m_mesh)

    def _mass_matrix(self):
        """
       In finite elements the grid does not have to be uniform
       That's why we have to use loops to assemble the matrices.
    """

        self.m_mass_diag = self.m_ass_stiff.get_mass_mat()

    def get_bd_conditions(self):
        """ dirichlet bc """

        return (self.m_ul, self.m_ur)

    def get_mesh(self):
        """ get solver's space grid."""

        return self.m_mesh

    def get_load_terms(self):
        """ return load pde's load term. """

        return oned_inner(self.m_basis, self.m_quads, self.m_mesh,
                          self.m_load)

    def get_mass_dformat(self):
        """ get mass matrix in diag format."""

        self.m_ass_stiff.discretize()
        return self.m_ass_stiff.get_mass_mat()

    def get_pdecos(self):
        """ Coeffients used to assemble the Matrices. """

        return self.m_ass_stiff.get_pdecos()

    def get_quads(self):
        """ get quadrature formulas. """

        return self.m_quads

    def get_sfunc(self):
        """ set shape functions."""

        return self.m_basis

    def get_stiff_dformat(self):
        """ get stiffness matrix in diag format."""

        self.m_ass_stiff.discretize()
        return self.m_ass_stiff.get_stiffness()

    def set_bd_conditions(self, uleft, uright):
        """ set boundary conditions. """

        (self.m_ul, self.m_ur) = (uleft, uright)

    def set_cos(self, diff, conv, reac, d_is_real=True,
            c_is_real=True, r_is_real=True):
        """ set pde coeffients. both real or splines. """
        self.m_ass_stiff.set_cos(diff, conv, reac, d_is_real,
                c_is_real, r_is_real)

    def set_sfunc_and_quads(self, basis, quads):
        """ set shape functions and quad formulas. """

        (self.m_basis, self.m_quads) = (basis, quads)
        self.m_ass_stiff.set_sfunc_and_quads(basis, quads)

    def set_load(self, load):
        """ set pde load. """

        self.m_load = load

    def solve(self):
        """ Assemble S and RHS.
            Only Dirichlet boundary condition is implemented.
        """

        self.m_ass_stiff.discretize()
        self.m_stiff_diag = self.m_ass_stiff.get_stiffness()

        stiff_diag = self.m_stiff_diag
        data = [list(stiff_diag[1:-1, 0].flatten()), list(stiff_diag[1:
                -1, 1].flatten()), list(stiff_diag[1:-1, 2].flatten())]
        diags = [0, 1, -1]

        rhs = self.get_load_terms()
        if 3 == self.m_basis.dof():
            data.append(list(stiff_diag[1:-1, 3].flatten()))
            data.append(list(stiff_diag[1:-1, 4].flatten()))
            diags.append(2)
            diags.append(-2)
            rhs[2] -= self.m_ul * stiff_diag[0, 4]
            rhs[-3] -= self.m_ur * stiff_diag[-1, 3]

        rhs[1] -= self.m_ul * stiff_diag[0, 2]
        rhs[-2] -= self.m_ur * stiff_diag[-1, 1]

        load = rhs[1:-1]
        gl_system = spdiags(asarray(data), asarray(diags), load.size,
                            load.size).tocsc()

        # Global solution.

        solu = zeros(rhs.shape)
        (solu[0], solu[-1]) = (self.m_ul, self.m_ur)
        solu[1:-1] = spsolve(gl_system, load).reshape((load.size, 1))
        return solu


    def space_discretize(self):
        """ discretize in space """

        self.m_ass_stiff.discretize()
        self.m_stiff_diag = self.m_ass_stiff.get_stiffness()


